<script setup lang="ts">
import router from '@/router';
import auth from '@/utils/auth';
import instance from '@/utils/http';
import type { AxiosError } from 'axios';
import { ElMessage } from 'element-plus'; // 正确导入 ElMessage
import type { FormInstance, FormRules } from 'element-plus';
import { ref } from 'vue';
import { ElCheckbox } from 'element-plus';
// 在这里导入所需的模块和组件
interface FormData {
  mobile: string;
  code: string;
}

const formData = ref<FormData>({
  mobile: '13888888888',
  code: '246810'
})

const formRules = ref<FormRules<FormData>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    // { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    //  len 设置验证规则的长度
    { len: 6, message: '验证码不正确', trigger: 'blur' }
  ]
})

const loginFormRef = ref<FormInstance>()

const submitForm = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 发送请求
        const res = await instance.post('/v1_0/authorizations', formData.value)
        localStorage.setItem('geek-client-vue3', res.data.data.token)
        auth.setToken(res.data.data.token)
        router.push('/')
        ElMessage.success('登录成功')
      } catch (e) {
        const errors = e as AxiosError<{ message: string }>;
        ElMessage.error(errors.response?.data.message || '登录失败')
      }
    }
  })
}
</script>

<template>
  <div class="container">
    <el-card>
      <!-- 图片 -->
      <img class="logo" src="@/assets/images/logo.png" alt="">
      <!-- 图标 -->
      <el-form ref="loginFormRef" :model="formData" :rules="formRules">
        <el-form-item prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input v-model="formData.code" placeholder="请输入验证码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox :value="true">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button @click="submitForm()" type="primary">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url(@/assets/images/login.png);

  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }

    .el-form {
      padding: 0 20px;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
